import router = require('plugins/router');
import ko = require('knockout');

import DiscoViewModel = require('../lib/discoViewModel');

import discussionVm  = require('../viewmodels/discussion');

import QuestionInfo = require('entities/questioninfo');

class Trend extends DiscoViewModel {

    public displayName: string = 'Trending';

    public questions: KnockoutObservableArray<QuestionInfo>;

    constructor() {
        super();

        this.questions = ko.observableArray<QuestionInfo>([]);

        this.discoContext.onReady(() => {
            console.debug('Data Context Ready.');

            var promise = this.initQuestions()
                .then((data) => { this.isLoading(false) });
        });
    }

    public select(question: QuestionInfo) {
        console.debug('Item Selected.');

        (<any>discussionVm).currentQuestion(question);

        router.activeItem(discussionVm);
        router.navigate('discussion/' + question.questionKey, { trigger: false, replace: false });
    }

    private initQuestions(): $data.IPromise<Disco.Ontology.Post[]> {
        console.debug('Initialize Questions..');

        var query = post => post.PostType.Description.Name in ['Question', 'Quintessence', 'Proposal'];

        var additionalImports: string[] = ['Ratings', 'ReferredFrom', 'ModifiedBy.Author', 'Tags.Description'];

        var promise = this.loadPosts(query, null, (data: Disco.Ontology.Post[]) => {
            data.forEach((post: Disco.Ontology.Post) => {
                this.questions.push(new QuestionInfo(post));
            });
        }, additionalImports);

        return promise;
    }
}

return new Trend();